package com.atguigu.lease.web.app.custom.interceptor;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.context.LoginUserContext;
import com.atguigu.lease.web.app.service.UserInfoService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("access_token");



        if (!StringUtils.hasLength(token)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }

        System.out.println("标点6");
        long userId = JwtUtil.getJwtToken(token);
        System.out.println("标点3");
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }

        System.out.println("标点2");

        if (info.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        System.out.println("得到数据");
        info.setPassword(null);

        LoginUserContext.setLoginUser(info);

        System.out.println("标点1");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
